import koa from 'koa';
import * as boom from '@hapi/boom';
import * as jwt from '../utils/jwt';
import * as userService from '../user/service.user';

function getToken(ctx: koa.Context): string | undefined {
  return ctx.cookies.get('token');
}

export async function auth(ctx: koa.Context, next: koa.Next) {
  const token = getToken(ctx);
  if (!token) {
    throw boom.unauthorized('尚未登录');
  }

  const payload = await jwt.verify(token);
  const user = await userService.findByUserId(payload.sub);
  if (!user) {
    throw boom.unauthorized('用户不存在');
  }
  ctx.user = user;
  await next();
}
